package com.cjx.stars.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.expression.engine.rhino.RhinoEngine;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cjx.stars.common.MyException;
import com.cjx.stars.common.Response;
import com.cjx.stars.common.ResponseUtils;
import com.cjx.stars.constant.FailMessage;
import com.cjx.stars.pojo.request.UpdatePasswordRequest;
import com.cjx.stars.pojo.table.User;
import com.cjx.stars.pojo.vo.UserVo;
import com.cjx.stars.pojo.request.Login;
import com.cjx.stars.pojo.request.Register;
import com.cjx.stars.service.UserService;
import com.cjx.stars.utils.AliyunSmsSenderUtil;
import com.cjx.stars.utils.RegexValidationUtils;
import com.cjx.stars.utils.UserHolder;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.cjx.stars.constant.FailMessage.*;
import static com.cjx.stars.constant.RedisConstant.USER_FORGET_PASSWORD_KEY;

/**
 * @author cjx
 * @description 用户
 * @createDate 2024/2/28 20:12
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;


    @PostMapping("/register")
    public Response<?> register(@RequestBody Register userRegister) {
        if (userRegister == null) {
            return ResponseUtils.fail(FailMessage.ERROR_PARAMETER_IS_BLACK);
        }
        return userService.register(userRegister);
    }

    @PostMapping("/login")
    public Response<?> login(@RequestBody Login userLogin) {
        if (userLogin == null) {
            return ResponseUtils.fail(FailMessage.ERROR_PARAMETER_IS_BLACK);
        }
        return userService.login(userLogin);
    }

    @GetMapping("/message")
    public Response<?> message(@RequestParam String phone) {
        if (StrUtil.isBlank(phone)) {
            return ResponseUtils.fail(FailMessage.ERROR_PARAMETER_IS_BLACK);
        }
        return userService.message(phone);
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    @GetMapping("/current")
    public Response<UserVo> current() {
        UserVo user = UserHolder.getUser();
        return ResponseUtils.success(user);
    }

    @PutMapping("/update/tags")
    public Response<?> updateTaps(@RequestBody ArrayList<String> tags, HttpServletRequest request) {
        UserVo user = UserHolder.getUser();
        if (tags == null) {
            return ResponseUtils.fail(FailMessage.ERROR_PARAMETER_IS_BLACK);
        }
        String token = request.getHeader("authorization");
        return userService.updateTags(tags, Long.valueOf(user.getUserId()), token);
    }

    @PostMapping("/logout")
    public Response<?> logout(HttpServletRequest request) {
        UserVo user = UserHolder.getUser();
        if (user == null) {
            return ResponseUtils.fail(FailMessage.ERROR_THE_USER_IS_NOT_LOGGED_IN);
        }
        return userService.logout(request);
    }

    @PutMapping("/update")
    public Response<?> update(@RequestBody UserVo updateUser, HttpServletRequest request) {
        if (updateUser == null) {
            return ResponseUtils.fail(FailMessage.ERROR_PARAMETER_IS_BLACK);
        }
        UserVo user = UserHolder.getUser();
        if (StringUtils.isNotBlank(updateUser.getEmail()) || StringUtils.isNotBlank(updateUser.getPhone())) {
            if (StringUtils.isBlank(updateUser.getCode())) {
                throw new MyException(NOT_CODE);
            } else {
                userService.updateUserWithCode(updateUser);
                return ResponseUtils.success();
            }
        }
        String token = request.getHeader("authorization");
        return userService.userUpdate(updateUser, Long.valueOf(user.getUserId()), token);
    }

    @GetMapping("/tags")
    public Response<?> getTags() {
        UserVo user = UserHolder.getUser();
        String tags = user.getTags();
        List<String> restoredArrayList = JSONUtil.toList(tags, String.class);
        return ResponseUtils.success(restoredArrayList);
    }

    @GetMapping("/search/tags")
    public Response<?> getSearchTags(@RequestParam int currentPage, @RequestParam ArrayList<String> tagNameList) {
        if (currentPage <= 0) {
            return ResponseUtils.fail(ERROR_INCORRECT_FORMAT);
        }
        if (tagNameList.isEmpty()) {
            return ResponseUtils.fail(FailMessage.ERROR_PARAMETER_IS_BLACK);
        }
        return userService.getSearchTags(currentPage, tagNameList);
    }

    @GetMapping("/match")
    public Response<?> matchUser(@RequestParam int currentPage, @RequestParam String username) {
        if (currentPage <= 0) {
            throw new MyException(ERROR_INCORRECT_FORMAT);
        }
        UserVo user = UserHolder.getUser();
        long userId = 0L;
        if (user != null) {
            userId = Long.parseLong(user.getUserId());
        }
        return ResponseUtils.success(userService.matchUser(currentPage, username, userId));
    }

    @GetMapping("/{userId}")
    public Response<?> getUser(@PathVariable("userId") Long userId) {
        if (!RegexValidationUtils.checkId(userId)) {
            throw new MyException(PARAMETER_ABNORMAL);
        }
        return userService.getDetailedUser(userId);
    }

    @GetMapping("/message/update/email")
    public Response<?> sendUpdateEmailCode(@RequestParam String email) {
        if (StrUtil.isBlank(email)) {
            throw new MyException(PARAMETER_ABNORMAL);
        }
        return userService.sendUpdateEmailCode(email);
    }

    /**
     * 获取用户通过电话
     *
     * @param phone 电话
     * @return {@link Response}<{@link String}>
     */
    @GetMapping("/forget")
    @ApiOperation(value = "通过手机号查询用户")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "phone", value = "手机号")})
    public Response<String> forgetUserPasswordSendPhoneCode(String phone) {
        if (phone == null) {
            throw new MyException(PARAMETER_ABNORMAL);
        }
        userService.forgetUserPasswordSendPhoneCode(phone);
            return ResponseUtils.success();
    }

    /**
     * 校验码
     *
     * @param phone 电话
     * @param code  代码
     * @return {@link Response}<{@link String}>
     */
    @GetMapping("/check")
    @ApiOperation(value = "校验验证码")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "phone", value = "手机号"),
                    @ApiImplicitParam(name = "code", value = "验证码")})
    public Response<String> checkCode(String phone, String code) {
        userService.checkCode(phone,code);
        return ResponseUtils.success();
    }

    /**
     * 更新密码
     *
     * @param updatePasswordRequest 更新密码请求
     * @return {@link Response}<{@link String}>
     */
    @PutMapping("/forget")
    @ApiOperation(value = "修改密码")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "updatePasswordRequest", value = "修改密码请求")})
    public Response<String> updatePassword(@RequestBody UpdatePasswordRequest updatePasswordRequest) {
        String phone = updatePasswordRequest.getPhone();
        String code = updatePasswordRequest.getCode();
        String password = updatePasswordRequest.getPassword();
        String confirmPassword = updatePasswordRequest.getConfirmPassword();
        if (StringUtils.isAnyBlank(phone, code, password, confirmPassword)) {
            throw new MyException(PARAMETER_ABNORMAL);
        }
        userService.updatePassword(phone, code, password, confirmPassword);
        return ResponseUtils.success();
    }

}
